<?php
/**
 * Created by PhpStorm.
 * User: liqiang
 * Date: 16-12-29
 * Time: 上午11:16
 */
namespace Inbound\Controller;

use Home\Controller\CommonController;
use Inbound\Service\PrepareneedsService;
use Inbound\Service\PublicInfoService;
use Inbound\Service\PublicPlugService;
use Inbound\Service\InboundshipmentplanService;
use Warehouse\Service\InventoryService;

class PrepareneedsController extends CommonController
{

    //备货需求服务层对象
    public $Prepareneeds = NULL;
    public $Inboundshipmentplan = NULL;
    public $inventory = null;
    //条件
    public $condition = array();

    //标志符
    public $flag;

    /**
     * 默认构造方法
     * khq 2016.12.29
     */
    public function __construct()
    {
        $this->Prepareneeds = D('Prepareneeds','Service');
        $this->Inboundshipmentplan = D('Inboundshipmentplan', 'Service');
        $this->inventory = D('Warehouse/Inventory', 'Service');
        parent::__construct();
    }

    /**
     * 备货需求初始界面
     * khq 2016.12.29
     */
    public function index()
    {
        $this->condition = $_GET;
        $result = $this->Prepareneeds->get_prepareneeds_data($_GET,true);
        $transder_arr = D('TransferHopperAddress','Service')->getTransferHopperAddress();
        $this->assign('transfer',$transder_arr);
        $this->assign('result',$result);
        $this->assign('page',$this->Prepareneeds->page);
        $this->assign('count',$this->Prepareneeds->count);
        $this->assign('orderState',PublicInfoService::get_prepareneeds_status_array());
        $this->display();
    }

    /**
     * 创建备货需求计划
     * khq 2016.12.29
     */
    public function create($_array = array(),&$model = NULL)
    {
        if($_POST){
            $sheetData = PublicPlugService::parse_excel();                            //解析excel内容

            if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
                if(count($sheetData)>=2){
                    $check_data = $this->Prepareneeds->check_upload_data($sheetData); // 检查导入的备货需求数据合法性
                    if(!$check_data['status']){
                        $transder_arr = D('TransferHopperAddress','Service')->getTransferHopperAddress();
                        $this->assign("result",$check_data['message']);
                        $this->assign('transfer',$transder_arr);
                        $this->display('Prepareneeds/create');
                        exit;
                    }
                    $result = $this->Prepareneeds->upload_platform($sheetData);       //最后解析数据,验证,更新数据库
                    switch ($result['status']){
                        case 401:
                            $this->assign("result","需求批次号生成失败,创建失败");
                            break;
                        case 402:
                            $this->assign("result","创建备货需求表失败,请稍后重试");
                            break;
                        case 403:
                            $this->assign("result","未知错误创建失败,请稍后重试");
                            break;
                        case 404:
                            $this->assign('result',$result['message']);
                            break;
                        case 200:
                            $this->assign("result","创建成功");
                            break;
                    }
                }else{
                    $this->assign("result","文件内容为空");
                }
            }else{
                $this->assign("result","请选择上传文件");
            }
        }
        $transder_arr = D('TransferHopperAddress','Service')->getTransferHopperAddress();
        $this->assign('transfer',$transder_arr);
        $this->display();
    }

    /**
     * 批量导入储位和预捡数量
     * khq 2017.1.12
     */
    public function create_storage()
    {
        if($_POST){
            $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
            if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
                if(count($sheetData)>=2){
                    $check_data = 
                        $this->Prepareneeds->check_create_storage_data($sheetData);   // 检查导入的备货需求数据合法性
                    if(!$check_data['status']){
                        $this->assign('result',$check_data['message']);
                        $this->display('Prepareneeds/create_storage');
                        exit;
                    }
                    $result = $this->Prepareneeds->upload_create_storage($sheetData); //最后解析数据,验证,更新储位和数量
                    $this->assign('result',$result['message']);
                }else{
                    $this->assign("result","文件内容为空");
                }
            }else{
                $this->assign("result","请选择上传文件");
            }
        }
        $this->display();
    }

    /**
     * ajax查询备货需求明细
     * khq 2016.1.12
     */
    public function ajax_select_detail()
    {
        $detail_data = $this->Prepareneeds->ajax_select_detail(array('id'=>$_GET['id']));
        $json_array = array(
            'status' => 'Y',
            'message'=> $detail_data
        );
        echo json_encode($json_array);
        exit;
    }

    /**
     * 查询单个备货需求明细
     * khq 2016.12.29
     */
    public function single_detail()
    {
        $this->condition = $_GET;
        $detail_data = $this->Prepareneeds->select_single_detail(array('batch_code'=>$_GET['batch_code']),false);
        if($_GET['downcsv']) $this->Prepareneeds->download_detail_typeone($detail_data); //详情导出
        $this->assign('create_user_id',$_GET['create_user_id']);
        $this->assign('result',$detail_data);
        $this->display();
    }

    /**
     * 备货需求明细
     */
    public function all_detail()
    {
        $this->condition = $_GET;
        if($_GET['downcsv']){
            unset($_GET['downcsv']);
            $result = $this->Prepareneeds->select_detail($_GET,false);                   //详情导出
            $this->Prepareneeds->download_detail($result);
        }
        if($_GET['downcsvother']){
            unset($_GET['downcsvother']);
            $result = $this->Prepareneeds->select_detail_other($_GET,false);                   //详情导出
            $this->Prepareneeds->download_detail_other($result);
        }
        $result = $this->Prepareneeds->select_detail($_GET,true);
        foreach($result as &$v){
            $relation = PublicInfoService::getOverseasSupervision($v['sku'], PublicInfoService::get_site_id($v['site_id']));
            $v['cargo_grade'] = $relation?$relation['cargo_grade']:$v['cargo_grade'];
        }
        $this->assign('result',$result);
        $this->assign('page',$this->Prepareneeds->page);
        $this->assign('count',$this->Prepareneeds->count);
        $this->assign('transport_way',PublicInfoService::get_transport_way_array());
        $this->assign('orderState',PublicInfoService::get_prepareneeds_status_array());
        $this->assign('sites',PublicInfoService::get_site_array());
        $this->assign('accounts',PublicInfoService::get_accounts());
        $this->display();
    }

    /**
     * 获取可以切换批次号的信息
     */
    public function changeCode()
    {
        C('LAYOUT_ON', false);
        if (isset($_POST['data']) && !empty($_POST['data'])) {
            $result = $this->Prepareneeds->getCodeInfo($_POST['data']);

            if ($result == 1) {
                echo $result;
            } elseif (!$result) {
                echo 2;
            } else {
                /*var_dump($result);exit;*/
                $this->assign('batch_codes', $result);
                $this->assign('needChangeCodeInfo', $_POST['data']);
                $content = $this->fetch();
                echo json_encode($content);
            }
        }
    }

    /**
     * 获取shipmentPlan的状态
     */
    public function getShipmentStatusByNeedDetailId() {
        $status = $this->Prepareneeds->prepareneedsdetailsshipmentid->getShipmentStatusByNeedDetailId($_GET['id']);

        echo $status;
    }

    /**
     * 更新批次号
     */
    public function updateBatchCode()
    {
        if (isset($_POST['data']) && !empty($_POST['data'])) {
            $result = $this->Prepareneeds->updateCode($_POST['data']);

            echo $result;
        }
    }

    /**
     * 更新状态为物流预审
     */
    public function logisticsPreview() {
        $result = $this->Prepareneeds->logisticsPreview($_POST['data']);

        echo $result ? 1 : 0;
        exit;
    }

    public function compliancePreview() {
        $result = $this->Prepareneeds->compliancePreview($_POST['data']);

        echo $result ? 1 : 0;
        exit;
    }

    /**
     * 导出备货需求计划模板
     * khq 2016.12.29
     */
    public function download()
    {
        PublicPlugService::download_templet();
    }
    
    /**
     * 销售核对
     * khq 2016.12.29
     */
    public function check_sale()
    {
        if($_GET['ids']=='' || $_GET['status']==''){
            $json_array = array(
                'status' => 'N',
                'message'=> '未选中单据!'
            );
            echo json_encode($json_array);
            exit;
        }

        $info = '';
        /*if ($_GET['status'] == 10) {
            $ids = explode(',', rtrim($_GET['ids'], ','));
            foreach ($ids as $id) {
                $data = $this->Prepareneeds->prepareneedsdetail->get_data_by_id($id);
                $needs_quantity = $data[0]['needs_quantity'];
                $condition = array(
                    'sku' => $data[0]['sku'],
                    'enterprise_dominant' => $data[0]['enterprise_dominant'],
                    'site_id' => $data[0]['site_id']
                );

                if ($data[0]['export_tax_rebate']) {
                    $quantity= $this->inventory->getTaxInventoriesInfo($condition);

                } else {
                    $quantity= $this->inventory->getInventoriesInfo($condition);
                }

                if ($quantity['actual_available_num'] < $needs_quantity) {
                    $info .= '[' .$data[0]['sku'] . ']:已经被占用</br>';
                }
            }
        }*/

        if (!empty($info)) {
            $json_array = array(
                'status' => 'N',
                'message'=> $info
            );
            echo json_encode($json_array);
            exit;
        }

        $result = $this->Prepareneeds->update_status($_GET);
        switch ($result){
            case 401:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选备货明细中上一阶段未审核完成,无法进行当前操作!'
                );
                break;
            case 402:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选单据已审核,请选择待核对明细!'
                );
                break;
            case 200:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '核对成功!'
                );
                break;
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '未知错误!'
                );
                break;
        }
        echo json_encode($json_array);
        exit;
    }
    /**
     * 仓库核对
     * khq 2016.12.29
     */
    public function check_warehouse()
    {
        if($_GET['ids']=='' || $_GET['status']==''){
            $json_array = array(
                'status' => 'N',
                'message'=> '未选中单据!'
            );
            echo json_encode($json_array);
            exit;
        }
        $result = $this->Prepareneeds->update_status($_GET);
        switch ($result){
            case 401:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选备货明细中上一阶段未审核完成,无法进行当前操作!'
                );
                break;
            case 402:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选单据已审核,请选择待核对明细!'
                );
                break;
            case 403:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '请先导入预捡数量和储位,再核对!'
                );
                break;
            case 200:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '核对成功!'
                );
                break;
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '未知错误!'
                );
                break;
        }
        echo json_encode($json_array);
        exit;
    }
    /**
     * 物流核对
     * khq 2016.12.29
     */
    public function check_transport()
    {
        if($_GET['ids']=='' || $_GET['status']==''){
            $json_array = array(
                'status' => 'N',
                'message'=> '未选中单据!'
            );
            echo json_encode($json_array);
            exit;
        }
        $result = $this->Prepareneeds->update_status($_GET);
        switch ($result){
            case 401:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选备货明细中上一阶段未审核完成,无法进行当前操作!'
                );
                break;
            case 402:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '所选单据已审核,请选择待核对明细!'
                );
                break;
            case 200:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '核对成功!'
                );
                break;
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '未知错误!'
                );
                break;
        }
        echo json_encode($json_array);
        exit;
    }

    /**
     * 创建FBA平台计划单
     */
    public function create_fba_stocking_plan()
    {
        $flag = $this->Prepareneeds->check_create_fba_data();
        $json_array = array();
        switch ($flag){
            case 401:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '多个备货计划不能一起创建平台计划单,请重新选择!'
                );
                break;
            case 402:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '取消的备货sku不能创建平台计划单,请重新选择!'
                );
                break;
            case 403:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '备货计划单据未审核完成,请先审核后再创建!'
                );
                break;
            case 404:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '只能选择同一账号的sku创建平台计划单,请重新选择!'
                );
                break;
            case 405:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '只能选择同一站点的sku创建平台计划单,请重新选择!'
                );
                break;
            case 406:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '备货明细中已生成平台计划单,不能重复创建!'
                );
                break;
            case 408:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '存在不同的物流渠道,请重新选择!'
                );
                break;
            case 200:
                $result = $this->Prepareneeds->create_fba_stocking_plan();
                switch ($result['status']){
                    case 200:
                        $json_array = array(
                            'status' => 'Y',
                            'message'=> '创建成功,生成shipmentid: '.$result['message']
                        );
                        break;
                    case 402:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> '账号id不存在'
                        );
                        break;
                    case 403:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> $result['message']. ' 基础资料不存在,请录入'
                        );
                        break;
                    case 404:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> $result['message']. ' 预捡数量不正确'
                        );
                        break;
                    case 405:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> 'API出错,'.$result['message']
                        );
                        break;
                    case 406:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> $result['message']. '的 title不存在,请录入'
                        );
                        break;
                    case 407:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> '美国站点不能创建平台计划单,请重新选择'
                        );
                        break;
                    case 401:
                    default:
                        $json_array = array(
                            'status' => 'N',
                            'message'=> '创建失败,请联系IT!'
                        );
                        break;
                }
        }
        echo json_encode($json_array);
        exit;
    }

    /**
     * 编辑单个明细信息
     * khq 2017.1.13
     */
    public function ajax_edit()
    {
        $edit_status = $this->Prepareneeds->ajax_edit();
        $json_array  = array();
        switch ($edit_status){
            case 401:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '当前状态不可编辑'
                );
                break;
            case 200:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '更新成功'
                );
                break;
            case 402:
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '更新失败'
                );
        }
        echo json_encode($json_array);
        exit;
    }

    /**
     * 取消明细
     * khq 2017.1.13
     */
    public function cancel()
    {
        $result_status = $this->Prepareneeds->cancel();
        $json_array = array();
        switch ($result_status){
            case 100:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '操作成功'
                );
                break;
            case 50:
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '当前状态不可编辑'
                );
                break;
        }
        echo json_encode($json_array);
        exit;

    }

    public function batch_cancel() {
        $result_status = $this->Prepareneeds->batch_cancel();

        switch ($result_status){
            case 100:
                $json_array = array(
                    'status' => 'Y',
                    'message'=> '操作成功'
                );
                break;
            case 50:
            default:
                $json_array = array(
                    'status' => 'N',
                    'message'=> '批量废除失败！'
                );
                break;
        }
        echo json_encode($json_array);
        exit;
    }

    /**
     * 描述：下载合规报表
     * 作者：橙子
     */
    public function download_compliance() {
        $this->Prepareneeds->download_compliance($_GET);
    }

    public function test()
    {
        print_r($_SESSION['current_account']);
        exit;

    }
    /**
     * 描述:PC单号查询
     * 作者:kelvin
     */
    public function pcSearch()
    {
        $model = M('prepare_needs_details','fba_','fbawarehouse');
        if(!$_GET || (!$_GET['pc_id'] && !$_GET['start_time'] && !$_GET['end_time'])){
            $this->display('pcSearch');die;
        }
        if($_GET['pc_id']){
            $where['pc_id'] = $this->Prepareneeds->format($_GET['pc_id']);
        }
        if(!$_GET['pc_id']){
            $where['pc_id'] = array('NEQ','');
        }
        if($_GET['start_time']){
            $where['a.create_time'][] = array('EGT',$_GET['start_time']);
        }
        if($_GET['end_time']){
            $where['a.create_time'][] = array('ELT',$_GET['end_time']);
        }
        $field ="a.pc_id,a.status,c.status as 'ship_status',a.sku,a.seller_sku,a.sku_name,c.shipmentid,a.site_id,
            a.account_id,a.account_name,a.create_time,s.asin,a.needs_quantity,a.export_tax_rebate,a.enterprise_dominant,
            a.claim_arrive_time,a.seller_check_time,a.compliance_check_time,a.logistic_check_time,a.over_time,
            c.create_time as 'plan_create_time',c.push_warehouse_time,c.picking_time,c.package_upload_time,a.create_user_id,
            box.create_time as 'box_create_time',tran.create_time as 'tran_create_time',tran.pickup_op_time";
        $list = $model->alias('a')
            ->join('LEFT JOIN fba_prepare_needs_details_shipmentid b ON b.prepare_needs_details_id = a.id')
            ->join('LEFT JOIN fba_inbound_shipment_plan c ON c.shipmentid = b.shipmentid')
            ->join('LEFT JOIN api_account_seller_sku s ON a.account_id = s.account_id AND a.seller_sku = s.seller_sku')
            ->join('LEFT JOIN fba_package_box box ON box.inbound_shipment_plan_id = c.id')
            ->join('LEFT JOIN fba_transport_plan tran ON tran.id = c.transport_plan_id')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->select();

//        echo $model->getLastSql();die;
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
//        $list = $model->alias('a')
//            ->join('LEFT JOIN fba_prepare_needs_details_shipmentid b ON b.prepare_needs_details_id = a.id')
//            ->join('LEFT JOIN fba_inbound_shipment_plan c ON c.shipmentid = b.shipmentid')
//            ->field("a.pc_id,a.status,c.status as 'ship_status',a.sku,a.seller_sku,a.sku_name,c.shipmentid,a.site_id,
//            a.account_name,a.create_time")
//            ->where($where)
//            ->limit($Page->firstRow.','.$Page->listRows)
//            ->select();
//dump($list);die;
        $rec = array();
        $ship_status = PublicInfoService::get_inbound_status();
        $site = PublicInfoService::get_site_array();
        foreach ($list as &$c){
            $c['end_status'] = $c['ship_status']?$ship_status[$c['ship_status']]:PublicInfoService::get_prepareneeds_status_by_id($c['status']);
            $c['site_id'] = $site[$c['site_id']];
            $c['create_user_id'] = PublicInfoService::get_user_name_by_id($c['create_user_id']);
            $c['export_tax_rebate'] = $c['export_tax_rebate']==1?'是':'否';
            $c['sku_name'] = str_replace("\n",'',$c['sku_name']);
            $c['enterprise_dominant'] = PublicInfoService::getCompanyName( $c['enterprise_dominant']);
            $c['seller_check_time'] = $c['seller_check_time']=='0000-00-00 00:00:00'?'':$c['seller_check_time'];
            $c['compliance_check_time'] = $c['compliance_check_time']=='0000-00-00 00:00:00'?'':$c['compliance_check_time'];
            $c['logistic_check_time'] = $c['logistic_check_time']=='0000-00-00 00:00:00'?'':$c['logistic_check_time'];
            $c['over_time'] = $c['over_time']=='0000-00-00 00:00:00'?'':$c['over_time'];
            $c['push_warehouse_time'] = $c['push_warehouse_time']=='0000-00-00 00:00:00'?'':$c['push_warehouse_time'];
            $c['picking_time'] = $c['picking_time']=='0000-00-00 00:00:00'?'':$c['picking_time'];
            $c['box_create_time'] = $c['box_create_time']=='0000-00-00 00:00:00'?'':$c['box_create_time'];
            $c['package_upload_time'] = $c['package_upload_time']=='0000-00-00 00:00:00'?'':$c['package_upload_time'];
            $c['tran_create_time'] = $c['tran_create_time']=='0000-00-00 00:00:00'?'':$c['tran_create_time'];
            $c['pickup_op_time'] = $c['pickup_op_time']=='0000-00-00 00:00:00'?'':$c['pickup_op_time'];
        }
        if($_GET['down']=='ok'){
            $this->Prepareneeds->downPcSearch($list);die;
        }
        foreach ($list as $k=> &$v){
            $rec[$v['pc_id']][] = $v;
        }

        $count      = count($rec);// 查询满足要求的总记录数
        $size = 10;
        $Page       = new \Think\Page($count,$size);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
        $result = $this->Prepareneeds->ownPage(isset($_GET['p'])?$_GET['p']:1,$size,$rec);
        $this->assign('rec',$result);
//        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->assign('size',$size);
        $this->assign('page',$show);// 赋值分页输出
        $this->display('pcSearch');
    }

} 